import React, { useReducer, useState } from 'react'
import Header from './components/Header'
import Login from './components/Login'
import Home from './components/Home'
import './App.css'
// 登录状态，天生需要共享
// createContext 内置方法
// 创建一个context 可以跨层级调用
// 在 context 父级 提供 context 输出
export const AuthContext = React.createContext();
// reducer 的一个初始值
const initialState = {
  isAuthenticated: false,
  user: null,
  token: null
}
// reducer 纯函数  状态机器，根据某一个状态改变，进入下一个状态
const reducer = (state, action) => {
  switch(action.type) {
    case 'LOGIN':
      return {
        ...state,
        isAuthenticated: action.payload.isAuthenticated,
        user: action.payload.user
      };
    case 'LOGOUT':
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        token: null
      };
    default:
      return state
  }
}

function App() {
  // initialState 初始值  
  // state reducer 状态树
  const [state, dispatch] = useReducer(reducer, initialState);
  console.log(state,'.....');
  return (
    <>
      <AuthContext.Provider value={{
        state,  // 共享数据的状态
        dispatch  // 修改状态的方法
      }}>
        <Header />
        <div className="App">{!state.isAuthenticated?<Login/>:<Home/>}</div>
      </AuthContext.Provider>
    </>
  )
}

export default App
